package com.howe.gateway.filter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Objects;

/**
 * @author zengwenhua
 * @datetime 2024/5/22 17:22
 * @description 认证过滤器
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@RequiredArgsConstructor
public class AuthFilter implements GlobalFilter {
    private static final AntPathMatcher ANT_PATH_MATCHER = new AntPathMatcher();

    /**
     * 过滤器
     *
     * @param exchange the current server exchange
     * @param chain    provides a way to delegate to the next filter
     * @return {@code Mono<Void>} to indicate when request handling is complete
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        String accessIp = Objects.requireNonNull(request.getRemoteAddress()).getAddress().getHostAddress();
        String path = request.getURI().getPath();

        log.debug("gateway entrance,path:{},ip:{},heads:{}", accessIp, path, request.getHeaders().entrySet());

        return chain.filter(exchange);
    }

    /**
     * 认证异常处理
     *
     * @param exchange
     * @param msg
     * @return
     */
    public static Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        ServerHttpRequest request = exchange.getRequest();
        List<String> authList = request.getHeaders().get(HttpHeaders.AUTHORIZATION);
        log.error("认证异常,请求路径:{},token:{}", exchange.getRequest().getPath(), authList);

        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        DataBuffer dataBuffer = response.bufferFactory().wrap(msg.getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }

    /**
     * 鉴权异常处理
     *
     * @param exchange
     * @param msg
     * @return
     */
    public static Mono<Void> forbiddenResponse(ServerWebExchange exchange, String msg) {
        log.error("鉴权异常,请求路径:{}", exchange.getRequest().getPath());

        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.FORBIDDEN);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        DataBuffer dataBuffer = response.bufferFactory().wrap(msg.getBytes());
        return response.writeWith(Mono.just(dataBuffer));
    }
}
